/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.engine.func;

import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;

import bsh.Interpreter;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author tangli
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-6-8 下午1:52:49          tangli         1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class CALC {
    private static Logger logger = Logger.getLogger(CALC.class);
    private static Interpreter interpreter;
    //    private static Interpreter tester;
    static {
        interpreter = new Interpreter();
        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(CALC.class.getResourceAsStream("functions.bsh"));
            interpreter.eval(reader);
        } catch (Exception e) {
            logger.error("fail to initial expression function libraries ", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("fail to close InputStreamReader ", e);
                }
            }
        }
    }

    public synchronized static Object calc(String expr) throws Exception {
        if (expr == null) {
            return null;
        }
        Object o = null;
        try {
            o = interpreter.eval(expr);
        } catch (Exception e) {
            String exceptionMessage = e.toString();
            if (exceptionMessage.contains("CAlC-001")) {
                throw new NullValueException(e);
            }
            throw new CalcException(e);
        }
        return o;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        String expr = "$1+1";
        try {
            interpreter.set("$1", "100");
            System.out.println(CALC.calc(expr));
        } catch (Exception e) {
            System.out.println(e.getClass());
            e.printStackTrace();
        }
    }

}
